package chapter08;

import java.io.*;

public class Java04_IO_File_Copy_Buffer {
    public static void main(String[] args) {
        // TODO Java IO - 文件复制 - 缓冲

        // 数据源文件对象
        File srcFile = new File("D:\\practiceCode\\java-top-speed\\data\\word.txt");
        // 数据目的地文件对象(自动生成)
        File destFile = new File("D:\\practiceCode\\java-top-speed\\data\\word.txt.copy");

        // 文件输入流（管道对象）
        FileInputStream in = null;
        // 文件输出流（管道对象）
        FileOutputStream out = null;

        // 缓冲输入流（管道对象）
        BufferedInputStream bufferedIn = null;
        // 文件输出流（管道对象）
        BufferedOutputStream bufferedOut = null;

        // TODO 缓冲区（水桶）
        byte[] cache = new byte[1024];

        try {
            in = new FileInputStream(srcFile);
            out = new FileOutputStream(destFile);

            bufferedIn = new BufferedInputStream(in);
            bufferedOut = new BufferedOutputStream(out);

            int data = -1;
            while ((data = bufferedIn.read(cache)) != -1) {
                bufferedOut.write(cache,0,data);
            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭管道
            if (bufferedIn != null) {
                try {
                    bufferedIn.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (bufferedOut != null) {
                try {
                    bufferedOut.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}
